<template>
  <div class="category-products-container">
    <div class="page-header">
      <div class="header-content">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/mall' }">学习商城</el-breadcrumb-item>
          <el-breadcrumb-item>{{ category.name }}</el-breadcrumb-item>
        </el-breadcrumb>
        <h1 class="category-title">{{ category.name }}</h1>
        <p class="category-description" v-if="category.description">{{ category.description }}</p>
      </div>
    </div>

    <div class="products-content">
      <!-- 筛选和排序 -->
      <div class="filter-bar">
        <div class="filter-left">
          <el-select v-model="filters.sortBy" placeholder="排序方式" @change="loadProducts">
            <el-option label="综合排序" value="default" />
            <el-option label="价格从低到高" value="price_asc" />
            <el-option label="价格从高到低" value="price_desc" />
            <el-option label="销量最高" value="sales" />
            <el-option label="评分最高" value="rating" />
            <el-option label="最新发布" value="createTime" />
          </el-select>
          
          <el-select v-model="filters.priceRange" placeholder="价格区间" @change="loadProducts">
            <el-option label="全部价格" value="" />
            <el-option label="0-50元" value="0-50" />
            <el-option label="50-100元" value="50-100" />
            <el-option label="100-200元" value="100-200" />
            <el-option label="200元以上" value="200+" />
          </el-select>
          
          <el-input
            v-model="filters.keyword"
            placeholder="搜索商品..."
            style="width: 300px"
            @keyup.enter="loadProducts"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-right">
          <el-radio-group v-model="viewMode" @change="handleViewModeChange">
            <el-radio-button label="grid">
              <el-icon><Grid /></el-icon>
            </el-radio-button>
            <el-radio-button label="list">
              <el-icon><List /></el-icon>
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="products-list" v-loading="loading">
        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="products-grid">
          <div 
            v-for="product in products"
            :key="product.id"
            class="product-card"
            @click="goToProductDetail(product.id)"
          >
            <div class="product-image">
              <img :src="product.image || '/images/default-product.png'" :alt="product.name" />
              <div class="product-overlay">
                <el-button type="primary" size="small">查看详情</el-button>
              </div>
              <div class="product-badges">
                <el-tag v-if="product.isHot" type="danger" size="small">热销</el-tag>
                <el-tag v-if="product.isNew" type="success" size="small">新品</el-tag>
                <el-tag v-if="product.discount" type="warning" size="small">{{ product.discount }}折</el-tag>
              </div>
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <p class="product-description">{{ product.description }}</p>
              <div class="product-meta">
                <el-rate v-model="product.rating" disabled show-score size="small" />
                <span class="sales-count">{{ product.salesCount || 0 }} 人购买</span>
              </div>
              <div class="product-price">
                <span class="current-price">¥{{ product.price }}</span>
                <span v-if="product.originalPrice > product.price" class="original-price">
                  ¥{{ product.originalPrice }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="products-table">
          <el-table :data="products" style="width: 100%">
            <el-table-column width="100">
              <template #default="{ row }">
                <img 
                  :src="row.image || '/images/default-product.png'" 
                  :alt="row.name"
                  class="table-product-image"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" min-width="200">
              <template #default="{ row }">
                <div class="product-name-cell">
                  <h4>{{ row.name }}</h4>
                  <p class="product-subtitle">{{ row.description }}</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" width="120">
              <template #default="{ row }">
                <div class="price-cell">
                  <span class="current-price">¥{{ row.price }}</span>
                  <span v-if="row.originalPrice > row.price" class="original-price">
                    ¥{{ row.originalPrice }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="评分" width="120">
              <template #default="{ row }">
                <el-rate v-model="row.rating" disabled size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="salesCount" label="销量" width="100" />
            <el-table-column label="标签" width="120">
              <template #default="{ row }">
                <el-tag v-if="row.isHot" type="danger" size="small">热销</el-tag>
                <el-tag v-if="row.isNew" type="success" size="small">新品</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="goToProductDetail(row.id)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && products.length === 0" class="empty-state">
          <el-empty description="暂无商品" />
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="total"
          :page-sizes="[12, 24, 48, 96]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadProducts(true)"
          @current-change="loadProducts(false)"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getProductsByCategory, getProductCategory } from '@/api/mall'

const route = useRoute()
const router = useRouter()

// 响应式数据
const category = ref({})
const products = ref([])
const loading = ref(false)
const total = ref(0)
const viewMode = ref('grid')

// 筛选条件
const filters = reactive({
  sortBy: 'default',
  priceRange: '',
  keyword: ''
})

// 分页参数
const pagination = reactive({
  page: 1,
  size: 24
})

// 页面加载
onMounted(async () => {
  await loadCategory()
  await loadProducts()
})

// 加载分类信息
const loadCategory = async () => {
  try {
    const response = await getProductCategory(route.params.categoryId)
    if (response.code === 200) {
      category.value = response.data
    }
  } catch (error) {
    console.error('获取分类信息失败:', error)
    ElMessage.error('获取分类信息失败')
  }
}

// 加载商品列表
const loadProducts = async (reset = false) => {
  if (reset) {
    pagination.page = 1
  }
  
  try {
    loading.value = true
    const response = await getProductsByCategory(route.params.categoryId, {
      ...filters,
      page: pagination.page,
      size: pagination.size
    })
    if (response.code === 200) {
      products.value = response.data.records || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 切换视图模式
const handleViewModeChange = () => {
  localStorage.setItem('mall-view-mode', viewMode.value)
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/mall/product/${productId}`)
}

// 初始化视图模式
const initViewMode = () => {
  const savedMode = localStorage.getItem('mall-view-mode')
  if (savedMode) {
    viewMode.value = savedMode
  }
}

// 初始化
initViewMode()
</script>

<style lang="scss" scoped>
.category-products-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
  padding: 40px 20px;
  
  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    
    .category-title {
      font-size: 32px;
      font-weight: 600;
      margin: 16px 0 8px 0;
    }
    
    .category-description {
      font-size: 16px;
      opacity: 0.9;
      margin: 0;
    }
  }
}

.products-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .filter-left {
    display: flex;
    gap: 16px;
    align-items: center;
  }
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  
  .product-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: transform 0.3s, box-shadow 0.3s;
    cursor: pointer;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(0,0,0,0.15);
      
      .product-overlay {
        opacity: 1;
      }
    }
    
    .product-image {
      position: relative;
      height: 200px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .product-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.7);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s;
      }
      
      .product-badges {
        position: absolute;
        top: 8px;
        left: 8px;
        display: flex;
        flex-direction: column;
        gap: 4px;
      }
    }
    
    .product-info {
      padding: 16px;
      
      .product-name {
        font-size: 16px;
        font-weight: 600;
        margin: 0 0 8px 0;
        color: #303133;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .product-description {
        color: #606266;
        margin: 0 0 12px 0;
        font-size: 14px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .product-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        
        .sales-count {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .product-price {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .current-price {
          font-size: 18px;
          font-weight: 600;
          color: #ff6b6b;
        }
        
        .original-price {
          font-size: 14px;
          color: #909399;
          text-decoration: line-through;
        }
      }
    }
  }
}

.products-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .table-product-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
  }
  
  .product-name-cell {
    h4 {
      margin: 0 0 4px 0;
      color: #303133;
    }
    
    .product-subtitle {
      margin: 0;
      color: #909399;
      font-size: 12px;
    }
  }
  
  .price-cell {
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    .current-price {
      font-size: 16px;
      font-weight: 600;
      color: #ff6b6b;
    }
    
    .original-price {
      font-size: 12px;
      color: #909399;
      text-decoration: line-through;
    }
  }
}

.empty-state {
  background: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.pagination {
  margin-top: 30px;
  text-align: center;
}

@media (max-width: 768px) {
  .page-header {
    padding: 20px 10px;
    
    .category-title {
      font-size: 24px;
    }
  }
  
  .products-content {
    padding: 10px;
  }
  
  .filter-bar {
    flex-direction: column;
    gap: 16px;
    
    .filter-left {
      flex-direction: column;
      width: 100%;
    }
  }
  
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 16px;
  }
}
</style>
